<template>
    <n-card style="margin-bottom: 16px">
        <n-tabs v-model:value="tabValue" justify-content="start" type="line" animated>
            <n-tab-pane name="articleList" tab="文章列表">
                <div v-for="(blog, index) in blogListIfo">
                    <n-card :title="blog.title" hoverable style="margin-bottom: 15px;">
                        <n-ellipsis :line-clamp="2" :tooltip="false">
                            {{ blog.content }}
                        </n-ellipsis>
                        <template #footer>
                            <n-flex :align="'center'">
                                <div>发布时间: {{ blog.update_time }}</div>
                                <n-button type="primary" @click="toUpdateArticle(blog)">修改</n-button>
                                <n-button type="error" @click="showDeleteDialog(blog)">删除</n-button>
                            </n-flex>
                        </template>
                    </n-card>
                </div>
                <n-flex :justify="'center'">
                    <n-pagination v-model:page="pageInfo.page" :page-count="pageInfo.pageCount" size="large"
                        show-quick-jumper show-size-picker :page-size="pageInfo.pageSize" :page-sizes="pageSizes"
                        @update:page="toPage" @update:page-size="setPageSize" :page-slot="7" />
                </n-flex>
            </n-tab-pane>
            <n-tab-pane name="addArticle" tab="添加文章">
                <n-form>
                    <n-form-item-row label="标题">
                        <n-input v-model:value="addArticleInfo.title" placeholder="请输入文章标题" />
                    </n-form-item-row>
                    <n-form-item-row label="分类">
                        <n-input-group>
                            <n-select v-model:value="addArticleInfo.categoryId" :options="categorySelectOptions"
                                placeholder="请选择文章分类" />
                        </n-input-group>
                    </n-form-item-row>
                    <n-form-item-row label="内容">
                        <TextEditor v-model:content="addArticleInfo.content"></TextEditor>
                    </n-form-item-row>
                </n-form>
                <n-button type="primary" block strong @click="uploadArticles">
                    提交
                </n-button>
            </n-tab-pane>
            <n-tab-pane name="updateArticle" tab="修改文章" disabled>
                <n-form>
                    <n-form-item-row label="标题">
                        <n-input v-model:value="updateArticleInfo.title" placeholder="请输入文章标题" />
                    </n-form-item-row>
                    <n-form-item-row label="分类">
                        <n-input-group>
                            <n-select v-model:value="updateArticleInfo.categoryId" :options="categorySelectOptions"
                                placeholder="请选择文章分类" />
                        </n-input-group>
                    </n-form-item-row>
                    <n-form-item-row label="内容">
                        <TextEditor v-model:content="updateArticleInfo.content"></TextEditor>
                    </n-form-item-row>
                </n-form>
                <n-button type="primary" block strong @click="updateArticles">
                    更新
                </n-button>
            </n-tab-pane>
        </n-tabs> </n-card>
</template>

<script setup>
import { ref, reactive, inject, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { NButton } from "naive-ui";
import { AdminStore } from "../../stores/AdminStore";
import TextEditor from "../../components/TextEditor.vue";

onMounted(() => {
    loadCategoryDatas()
    loadBlogDatas()
})

const router = useRouter()
const route = useRoute()

const adminStore = AdminStore()

const axios = inject('axios')
const message = inject('message')
const dialog = inject('dialog')

const tabValue = ref('articleList')
const categorySelectOptions = ref([])
const blogListIfo = ref([])
const pageSizes = ref([
    {
        label: '5 每页',
        value: 5
    },
    {
        label: '10 每页',
        value: 10
    }
])
const pageInfo = reactive({
    page: 1, // 第几页
    pageSize: 5, // 每页几条数据
    count: 0,// 全页总数据
    pageCount: 0, // 有几页
})
const addArticleInfo = reactive({
    title: "",
    categoryId: null,
    content: ""
})
const updateArticleInfo = reactive({
    id: "",
    title: "",
    categoryId: null,
    content: ""
})

const setPageSize = (pageSize) => {
    pageInfo.pageSize = pageSize;
    loadBlogDatas()
}

const toScrollTop = () => {
    if (document.body.scrollTop) {
        document.body.scrollTop = 0
    } else {
        document.documentElement.scrollTop = 0
    }
}

const loadBlogDatas = async () => {
    try {
        let res = await axios.get("/api/blog/list", { params: { page: pageInfo.page, pageSize: pageInfo.pageSize } })
        let temp_rows = res.data.data
        for (let row of temp_rows) {
            row.content += '...'
            row.update_time = new Date(row.update_time).toLocaleString()
        }
        pageInfo.count = res.data.count
        pageInfo.pageCount = Math.ceil(pageInfo.count / pageInfo.pageSize)
        blogListIfo.value = temp_rows
        console.log(temp_rows);
        toScrollTop()
        // message.success("数据获取成功");
    } catch (error) {
        console.log(error.response.data);
        message.error("数据获取失败");
    }
}

const toPage = async (pageNum) => {
    pageInfo.page = pageNum
    loadBlogDatas()
}

const loadCategoryDatas = async () => {
    try {
        let res = await axios.get("/api/category/list")
        console.log(res.data._dbres);
        categorySelectOptions.value = res.data._dbres.map(item => {
            return {
                label: item.name,
                value: item.id
            }
        })
    } catch (error) {
        console.log(error.response.data);
        message.error(error.response.data.msg);
    }
}

const uploadArticles = async () => {
    if (!addArticleInfo.content.trim() || !addArticleInfo.title.trim()) {
        message.error('内容和标题不能为空');
        return
    }
    try {
        let res = await axios.post('/api/blog/_token/add',
            {
                title: addArticleInfo.title,
                category_id: addArticleInfo.categoryId,
                content: addArticleInfo.content,
            })
        console.log(res);
        message.success(res.data.msg);
        addArticleInfo.title = "";
        addArticleInfo.categoryId = null;
        addArticleInfo.content = "";
        tabValue.value = 'articleList'
        loadBlogDatas()
    } catch (error) {
        console.log(error.response.data);
        message.error(error.response.data.msg);
    }
}

const toUpdateArticle = async (articleInfo) => {
    try {
        let res = await axios.get("/api/blog/detail", { params: { id: articleInfo.id } })
        let temp_row = res.data.data[0]
        console.log(res);
        updateArticleInfo.id = articleInfo.id
        updateArticleInfo.title = temp_row.title
        updateArticleInfo.categoryId = temp_row.category_id
        updateArticleInfo.content = temp_row.content
        tabValue.value = 'updateArticle'
        toScrollTop()
    } catch (error) {
        console.log(error);
        message.error("数据获取失败");
    }
}

const updateArticles = async () => {
    try {
        let res = await axios.post("/api/blog/_token/update", {
            id: updateArticleInfo.id,
            title: updateArticleInfo.title,
            category_id: updateArticleInfo.categoryId,
            content: updateArticleInfo.content
        })
        console.log(res);
        tabValue.value = 'articleList'
        loadBlogDatas()
        message.success(res.data.msg);
    } catch (error) {
        console.log(error.response.data);
        message.error("更新失败");
    }
}

const showDeleteDialog = (row) => {
    // console.log(row);
    dialog.warning({
        title: "警告",
        content: "是否要删除",
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
            DeleteArticles(row)
        },
        onNegativeClick: () => { }
    });
}

const DeleteArticles = async (row) => {
    try {
        let res = await axios.post('/api/blog/_token/delete', { id: row.id })
        console.log(res);
        loadBlogDatas()
        message.success(res.data.msg);
    } catch (error) {
        console.log(error);
        message.error(error.response.data.msg);
    }
}

</script>

<style scoped>
.card-tabs .n-tabs-nav--bar-type {
    padding-left: 4px;
}
</style>